package com.example.travelservlet.scenery.service;

import com.example.travelservlet.entity.City;
import com.example.travelservlet.entity.Scenery;
import com.example.travelservlet.scenery.repository.SceneryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 30697
 */
@Service
public class SceneryServiceImpl implements SceneryService{

    @Autowired
    private SceneryRepository sceneryRepository;

    @Override
    public Page findSceneriesByCityIdAndSceneryIds(City city, List<String> sceneryIds, Pageable pageable) {
        Specification specification = new Specification<Scenery>() {
            @Override
            public Predicate toPredicate(Root<Scenery> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.equal(root.get("cityId"),city.getCityId()));
                if (sceneryIds.size() != 0) {
                    for (String sceneryId : sceneryIds) {
                        predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("sceneryId"),sceneryId)));
                    }

                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return sceneryRepository.findAll(specification, pageable);
    }

    @Override
    public List<Scenery> findSceneriesBySceneryIds(List<String> sceneryIds,Sort sort) {
//        Sort.Order collectOrder = Sort.Order.desc("collectTime");
//        Sort sort = Sort.by(collectOrder);

        return sceneryRepository.findSceneriesBySceneryIdIsIn(sceneryIds,sort);
    }
}
